var app = getApp(); //获取应用实例
const pathLevel = '../../../../'; //路径层级
const quote = require(pathLevel + 'utils/quote.config.js') //统一引入文件
const tools = quote.tools;
const mta = quote.mta;
const api = quote.api;
const path = quote.paths;

Page({
    data: {
        path: path,
        QID: null,
        VID: null, //每日一句句子ID
        sharerId: '',
        isCurrentbtnClick: false, //当前挑战榜按钮是否已经点击
        ThisRanking: 0, //用户本次排名
        ThisScore: 0, //用户本次得分
        todayScoreRankingList: [], //今日得分榜
        todayScoreRankingPageIndex: 0, //今日排行榜页面页码
        isTodaybtnClick: false, //今日榜按钮是否已经点击
        yesterdayScoreRankingList: [], //昨日得分榜
        yesterdayScoreRankingPageIndex: 0, //昨日排行榜页面页码
        isYesterdaybtnClick: false, //昨日榜按钮是否已经点击
        rewardRankingList: [], //奖金榜
        rewardRankingPageIndex: 0, //奖金排行榜页面页码
        CurrentUserReward: 0, //当前用户的奖金
        isRewardbtnClick: false, //奖励榜按钮是否已经点击
        hideChallenge: false,
        hideToday: false,
        hideYesterday: true,
        counts: 0, //练习次数
        loadingHidden: false,
        notToEnd: true, //没有到底
        avatarUrl: null, //用户头像
        hideModal: true
    },
    onLoad: function(options) {
        // 生命周期函数--监听页面加载
        var that = this;
        console.log('加载每日挑战页获取到的数据', options)
        mta.Page.init();

        that.setData({
            QID: options.QID || null,
            sharerId: options.sharerId || null,
            VID: options.VID || null
        })

        //获取今日排行榜数据
        that.gettodaydata(function(res) {
            // that.setData({
            //     loadingHidden: true,
            // })
        }, false);

    },
    onReady: function() {
        // 生命周期函数--监听页面初次渲染完成
        var that = this;

        // wx.showLoading({
        //     title: '加载中...'
        // })
    },
    onShow: function() {
        // 生命周期函数--监听页面显示
        var that = this;

        tools.getPracticeTimes({ OpenId: app.globalData.openId, UID: app.globalData.UID }, function(res) {
            if (res.data.code != 0) {
                return
            }
            app.globalData.AccountsTimes = res.data.data || 0;
            that.setData({
                counts: app.globalData.loginStatus ? app.globalData.AccountsTimes + app.globalData.DefaultTimes : app.globalData.DefaultTimes || 0
            })
        })
        setTimeout(() => {
            that.setData({
                avatarUrl: app.globalData.userInfo.avatarUrl
            })
        }, 1000);
    },
    onHide: function() {
        // 生命周期函数--监听页面隐藏

    },
    onUnload: function() {
        // 生命周期函数--监听页面卸载

    },
    onPullDownRefresh: function(res) {
        // 页面相关事件处理函数--监听用户下拉动作
        console.log('你刚刚执行力下拉操作', res)

    },
    onReachBottom: function() {
        // 页面上拉触底事件的处理函数

    },

    queryDate: function(num = 0) {
        var nowDate = new Date();
        var month = nowDate.getMonth() + 1;
        var day = (nowDate.getDate() + num) > 1 ? (nowDate.getDate() + num) : 1;
        var str = nowDate.getFullYear() + "-" + month + "-" + day;
        return str;
    },

    //点击挑战榜按钮
    getcurrentdata: function(obj) {
        var that = this;

        //挑战榜按钮已被点击
        if (that.data.isCurrentbtnClick) {
            return
        }

        that.setData({
            isCurrentbtnClick: true,
            isRewardbtnClick: false,
            hideChallenge: false,
            notToEnd: true,
        })
    },

    //点击奖金排行榜
    getrewarddata: function(obj) {
        var that = this;

        app.aldstat.sendEvent('挑战排行榜-点击奖励排行');
        mta.Event.stat("dailyChallenge_clickgetrewarddata", {});

        //奖金榜按钮已被点击
        if (that.data.isRewardbtnClick) {
            return
        }
        that.setData({
            isRewardbtnClick: true,
            isCurrentbtnClick: false,
            notToEnd: true,
        })

        if (that.data.rewardRankingList.length > 0) {
            that.setData({
                hideChallenge: true
            })
            return
        }

        that.getMoneyAwardList(that.data.rewardRankingPageIndex, function(res) {
            console.log('奖金榜的数据', res.data.data);
            var data = res.data.data;
            var rewardRankingList = that.data.rewardRankingList.concat(data.AllUsersRewardList);
            that.setData({
                CurrentUserReward: data.CurrentUserReward,
                rewardRankingList: rewardRankingList,
                hideChallenge: true
            })
        });

    },

    //点击今日排行榜数据
    gettodaydata: function(cb, showLoading = true) {
        var that = this;

        //今日榜按钮已被点击
        if (that.data.isTodaybtnClick) {
            return
        }
        that.setData({
            isTodaybtnClick: true,
            isYesterdaybtnClick: false,
            notToEnd: true,
        })

        if (that.data.todayScoreRankingList.length > 0) {
            that.setData({
                hideToday: false
            });
            return
        }

        that.getDailyChallengeRanking(0, 0, function(res) {
            console.log('点击今日排行榜按钮获取的数据', res.data.data.ChallengeRankings);
            var data = res.data.data.ChallengeRankings;
            var todayScoreRankingList = that.data.todayScoreRankingList.concat(data.CurrentRankingsList);
            that.setData({
                todayScoreRankingList: todayScoreRankingList, //用户得分列表
                ThisRanking: data.ThisRanking, //用户本次排名
                ThisScore: data.ThisScore, //用户本次得分
            });
            typeof cb == 'function' && cb(res);
        }, showLoading)
        that.setData({
            hideToday: false
        });

    },

    //点击昨日排行榜数据
    getyesterdaydata: function(cb) {
        var that = this;

        app.aldstat.sendEvent('挑战排行榜-点击昨日排行榜');
        mta.Event.stat("dailyChallenge_clickgetyesterdaydata", {})

        //昨日榜按钮已被点击
        if (that.data.isYesterdaybtnClick) {
            return
        }
        that.setData({
            isYesterdaybtnClick: true,
            isTodaybtnClick: false,
            notToEnd: true,
        })

        if (that.data.yesterdayScoreRankingList.length > 0) {
            that.setData({
                hideToday: true
            });
            return
        }

        that.getDailyChallengeRanking(-1, 0, function(res) {
            console.log('点击昨日排行榜按钮获取的数据', res.data.data.ChallengeRankings);
            var data = res.data.data.ChallengeRankings;
            if (data.CurrentRankingsList.length == 0) {
                console.log('昨天没有练习');
            } else {
                var yesterdayScoreRankingList = that.data.yesterdayScoreRankingList.concat(data.CurrentRankingsList);
                that.setData({
                    yesterdayScoreRankingList: yesterdayScoreRankingList, //用户得分列表
                });
            }
            typeof cb == 'function' && cb();
        })
        that.setData({
            hideToday: true
        });
    },

    //获取奖金排行榜函数
    getMoneyAwardList: function(index, cb) {
        var that = this;

        wx.showLoading({
            title: '加载中...',
        });
        api.methodGetDailyRewardRankingList({
            dataDic: {
                OpenId: app.globalData.openId,
                PageIndex: index || 0,
                PageSize: 100
            },
            success: function(res) {
                console.log('获取数据成功', res)
            },
            complete: (res) => {
                wx.hideLoading();
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    console.log('奖励排行榜数据', res);
                    typeof cb == 'function' && cb(res);
                }
            }
        })
    },

    //获取某日挑战榜函数
    getDailyChallengeRanking: function(date, index, cb, showLoading = true) {
        var that = this;

        showLoading && wx.showLoading({
            title: '加载中...',
        });
        api.methodGetDailyChallengeRankingList({
            dataDic: {
                OpenId: app.globalData.openId,
                // QID: that.data.QID,
                Date: that.queryDate(date),
                PageIndex: index || 0,
                PageSize: 50,
            },
            complete: (res) => {
                console.log('挑战排行榜数据请求完成', res);
                wx.hideLoading();
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    var data = res.data.data.ChallengeRankings;
                    that.setData({
                        ThisScore: data.ThisScore,
                        ThisRanking: data.ThisRanking,
                        loadingHidden: true
                    })
                    typeof cb == 'function' && cb(res);
                }
            }
        })
    },

    //再练一次
    onceMore: function() {
        var that = this;

        app.aldstat.sendEvent('挑战排行榜-点击再次挑战-成功');
        mta.Event.stat("dailyChallenge_clickonceMore", {})

        if (app.globalData.loginStatus) {
            if (that.data.counts < 1) {
                app.aldstat.sendEvent('挑战排行榜-点击再次挑战-提示用户去分享');
                wx.showModal({
                    title: '提示',
                    content: '你的挑战次数为零,点击分享按钮获得更多练习机会',
                    showCancel: false,
                    success: function(res) {
                        if (res.confirm) {
                            console.log('用户点去分享');
                            that.toShare();

                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                })
                return
            }
            wx.redirectTo({
                url: `/${path.spokenPk}?VID=${that.data.VID}`
            })

        } else {
            app.aldstat.sendEvent('挑战排行榜-点击再次挑战-提示用户登录');
            wx.showModal({
                title: '提示',
                content: '再次挑战需登录',
                showCancel: false,
                success: function(res) {
                    if (res.confirm) {
                        console.log('用户点击登录')
                        wx.navigateTo({
                            url: `/${path.login}?fromPage=dailyChallenge`,
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        }

    },

    //昨日榜触底函数
    yesterdayLower: function(e) {
        var that = this;

        console.log(e);
        if (!that.data.notToEnd) {
            return
        }
        that.setData({
            yesterdayScoreRankingPageIndex: that.data.yesterdayScoreRankingPageIndex + 1
        });
        that.getDailyChallengeRanking(-1, that.data.yesterdayScoreRankingPageIndex, function(res) {
            console.log('昨日榜触底返回的数据', res);
            var data = res.data.data.ChallengeRankings;
            if (data.CurrentRankingsList.length >= 0) {
                that.setData({
                    notToEnd: false
                })
                return
            }
            var yesterdayScoreRankingList = that.data.yesterdayScoreRankingList.concat(data.CurrentRankingsList);
            that.setData({
                yesterdayScoreRankingList: yesterdayScoreRankingList,
            })
        })
    },

    //今日榜触底函数
    todayLower: function(e) {
        var that = this;

        console.log(e);
        if (!that.data.notToEnd) {
            return
        }
        that.setData({
            todayScoreRankingPageIndex: that.data.todayScoreRankingPageIndex + 1
        });
        that.getDailyChallengeRanking(0, that.data.todayScoreRankingPageIndex, function(res) {
            console.log('今日榜触底返回的数据', res);
            var data = res.data.data.ChallengeRankings;
            if (data.CurrentRankingsList.length >= 0) {
                that.setData({
                    notToEnd: false
                })
                return
            }
            var todayScoreRankingList = that.data.todayScoreRankingList.concat(data.CurrentRankingsList);
            that.setData({
                todayScoreRankingList: todayScoreRankingList,
            })
        })
    },

    //奖金榜触底执行函数
    rewardLower: function(e) {
        var that = this;

        console.log(e);
        if (!that.data.notToEnd) {
            return
        }
        that.setData({
            rewardRankingPageIndex: that.data.rewardRankingPageIndex + 1
        });
        that.getMoneyAwardList(that.data.rewardRankingPageIndex, function(res) {
            console.log('奖金榜触底返回的数据', res);
            var data = res.data.data;
            if (data.AllUsersRewardList.length >= 0) {
                that.setData({
                    notToEnd: false
                })
                return
            }
            var rewardRankingList = that.data.rewardRankingList.concat(data.AllUsersRewardList);
            that.setData({
                rewardRankingList: rewardRankingList,
            })
        })
    },

    //去分享
    toShare: function() {
        var that = this;

        app.aldstat.sendEvent('挑战排行榜-点击分享');
        mta.Event.stat('dailyChallenge_clicktoShare', {})
    },

    //弹出海报
    popupPoster: function(params) {
        var that = this;

        app.aldstat.sendEvent('排行榜-点击口语训练营');
        mta.Event.stat('dailyChallenge_clickpopupPoster', {})

        wx.navigateTo({
            url: `/${path.spokenTraining}`,
        })

    },

    onShareAppMessage: function(res) {
        var that = this;

        if (app.globalData.loginStatus) {
            app.aldstat.sendEvent('挑战排行榜-点击分享（已登录）');
            mta.Event.stat('dailyChallenge_clicktoShare_login', {})
            return {
                title: '练口语得奖金，一起来PK吧！',
                path: `${path.index}?shareOpenId=${app.globalData.openId}&QID=${that.data.QID}&shareUID=${app.globalData.UID}&sharePath=dailyChallenge&Dailychallenge=1`,
                imageUrl: path.images + 'sharebanner.jpg',
                success: function(res) {
                    console.log('分享成功');
                    wx.showShareMenu({
                        withShareTicket: true
                    })
                    app.aldstat.sendEvent('挑战排行榜-点击分享（已登录）-分享成功');
                }
            }

        } else {
            app.aldstat.sendEvent('挑战排行榜-点击分享（未登录）');
            mta.Event.stat('dailyChallenge_clicktoShare_notlogin', {})
            return {
                title: '练口语得奖金，一起来PK吧！',
                path: `${path.index}?shareOpenId=${app.globalData.openId}&QID=${that.data.QID}&shareUID=${app.globalData.UID}&sharePath=dailyChallenge&Dailychallenge=1`,
                imageUrl: path.images + 'sharebanner.jpg',
                success: function(res) {
                    console.log('分享成功');
                    wx.showShareMenu({
                        withShareTicket: true
                    })
                    app.aldstat.sendEvent('挑战排行榜-点击分享（未登录）-分享成功');
                }
            }
        }

    },

})